import { Command } from 'commander';
import inquirer from 'inquirer';
import { api } from '../services/api';
import { config } from '../services/config';
import { logger } from '../utils/logger';
import { validateEmail, validatePhone, isEmailOrPhone } from '../utils/validation';
import { CLIError } from '../types';

export function authCommands(program: Command): void {
  program
    .command('login')
    .description('Login to the platform using email/phone + verification code')
    .option('-u, --user <emailOrPhone>', 'Email address or phone number')
    .action(async (options) => {
      try {
        let { user: emailOrPhone } = options;

        if (!emailOrPhone) {
          const answers = await inquirer.prompt([
            {
              type: 'input',
              name: 'emailOrPhone',
              message: 'Email or Phone:',
              validate: (input: string) => {
                const type = isEmailOrPhone(input);
                if (!type) {
                  return 'Please enter a valid email address or phone number';
                }
                return true;
              }
            }
          ]);
          emailOrPhone = answers.emailOrPhone;
        }

        const inputType = isEmailOrPhone(emailOrPhone);
        if (!inputType) {
          throw new CLIError('Invalid email or phone number format');
        }

        // 发送验证码
        const sendSpinner = logger.spinner('Sending verification code...');
        try {
          if (inputType === 'phone') {
            await api.sendSmsCode(emailOrPhone);
          } else {
            await api.sendEmailCode(emailOrPhone);
          }
          sendSpinner.succeed(`Verification code sent to ${emailOrPhone}`);
        } catch (error) {
          sendSpinner.fail();
          throw new CLIError('Failed to send verification code');
        }

        // 输入验证码
        const { code } = await inquirer.prompt([
          {
            type: 'input',
            name: 'code',
            message: 'Verification Code:',
            validate: (input: string) => {
              if (!input || input.length !== 6) {
                return 'Please enter a 6-digit verification code';
              }
              return true;
            }
          }
        ]);

        // 验证码登录
        const loginSpinner = logger.spinner('Logging in...');
        try {
          let result;
          if (inputType === 'phone') {
            result = await api.codeLogin(emailOrPhone, code);
          } else {
            result = await api.emailCodeLogin(emailOrPhone, code);
          }
          
          config.setToken(result.token);
          loginSpinner.succeed();
          logger.success(`Welcome, ${result.user.name}! (${emailOrPhone})`);
        } catch (error) {
          loginSpinner.fail();
          throw error;
        }
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Login failed. Please check your verification code.');
      }
    });

  program
    .command('logout')
    .description('Logout from the platform')
    .action(async () => {
      try {
        config.removeToken();
        config.delete('currentProject');
        logger.success('Logged out successfully');
      } catch (error) {
        logger.error('Failed to logout');
      }
    });

  program
    .command('whoami')
    .description('Display current user information')
    .action(async () => {
      try {
        const token = config.getToken();
        if (!token) {
          logger.error('Not logged in. Use "cm login" to authenticate.');
          return;
        }

        const spinner = logger.spinner('Fetching user information...');
        try {
          const user = await api.getMe();
          spinner.succeed();
          
          logger.log(`\nUser Information:`);
          logger.log(`Name: ${user.name}`);
          logger.log(`Email: ${user.email}`);
          logger.log(`Organizations: ${user.organizations.join(', ') || 'None'}`);
          
          const currentProject = config.getCurrentProject();
          const currentEnv = config.getCurrentEnvironment();
          
          logger.log(`\nCurrent Context:`);
          logger.log(`Project: ${currentProject || 'None'}`);
          logger.log(`Environment: ${currentEnv}`);
        } catch (error) {
          spinner.fail();
          throw error;
        }
      } catch (error) {
        if (error instanceof CLIError) {
          throw error;
        }
        throw new CLIError('Failed to get user information');
      }
    });
}